package tieba.web;

import java.io.UnsupportedEncodingException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import tieba.core.CookieUtils;
import tieba.core.JsonUtils;
import tieba.core.TBApi;
import tieba.entity.TbUser;
import tieba.service.ICmsUserService;
import tieba.service.ITbUserService;
import tieba.web.entity.ResultType;
import cl.tools.http.method.BasicMethod;

import com.jayway.restassured.response.Response;

@Controller
@RequestMapping("/bduser")
public class BdUserController {

	@Resource
	private ITbUserService tbUserService;
	@Resource
	private ICmsUserService cmsUserService;

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login() {
		return "menu/bdlogin";
	}

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public @ResponseBody ResultType login(TbUser user, HttpServletRequest req) {
		Response resp = null;
		if (user.getBAIDUID() != null && !"".equals(user.getBAIDUID().trim())) {
			user.getCookies().put("BAIDUID", user.getBAIDUID());
		}
		if ((resp = BasicMethod.postJson(TBApi.CORE + "/login", user))
				.getStatusCode() == 200) {
			TbUser u = JsonUtils.jsonToObj(resp.asString(), TbUser.class);
			if (u.getBduss() != null && !"".equals(u.getBduss().trim())) {
				u.setCmsUser(CookieUtils.isLogin(req, cmsUserService));
				tbUserService.save(u);
				return new ResultType(0, "SUCCESS", null);
			}
		}
		return JsonUtils.jsonToObj(resp.asString(), ResultType.class);
	}

	@RequestMapping(value = "/sign", method = RequestMethod.GET)
	public String sign() {
		return "menu/bdlogin";
	}

	@RequestMapping(value = "/sign_one/{id}/{fn}", produces = { "application/json;charset=UTF-8" }, method = RequestMethod.GET)
	public @ResponseBody String signOne(@PathVariable("id") int id,
			@PathVariable("fn") String fn, HttpServletRequest req) {
		System.out.println(fn);
		String body = BasicMethod.get(
				TBApi.SIGN + "/" + fn + "/"
						+ tbUserService.findById(id).getBduss()).asString();
		return body;
	}

	@RequestMapping(value = "/remove/{id}", method = RequestMethod.GET)
	public String remove(@PathVariable("id") int id) {
		tbUserService.remove(tbUserService.findById(id));
		return "redirect:/menu";

	}
}
